package com.sky.web.admin;

import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageDTO;
import com.sky.entity.Setmeal;
import com.sky.result.PageBean;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    // 分页查询
    @GetMapping("/page")
    public Result findByPage(SetmealPageDTO dto) {
        PageBean<SetmealVO> pageBean = setmealService.findByPage(dto);
        return Result.success(pageBean);
    }

    // 新增
    @PostMapping
    @CacheEvict(value = "setmealCache", key = "#setmealDTO.categoryId")
    public Result save(@RequestBody @Validated(SetmealDTO.Save.class) SetmealDTO dto) {
        setmealService.save(dto);
        return Result.success();
    }

    // 根据id查询套餐
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        SetmealVO setmealVO = setmealService.findById(id);
        return Result.success(setmealVO);
    }

    // 修改套餐
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result update(@RequestBody @Validated(SetmealDTO.Update.class) SetmealDTO dto) {
        setmealService.update(dto);
        return Result.success();
    }


    //状态的启动禁用
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result updateById(Long id ,@PathVariable("status") Integer status) {
        //1.构建setmealDTO对象
        Setmeal setmeal = Setmeal.builder().id(id).status(status).build();
        //2.调用service更新
        setmealService.updateById(setmeal);
        return Result.success();
    }

    //批量删除套餐
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result deleteByIds(Long[] ids) {
        setmealService.deleteByIds(ids);
        return Result.success();
    }
}

